from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.dataCheck import DataCheck
from user.models import IPSystem, User
from log.models import UserLog
from system.models import System
from django.db.models import Q
from storehouse.models import Storehouse, StorehouseConnect
import pdb, os, json, requests
import psutil
import logging
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")

datacheck = DataCheck()


def IPOperate(request, *args, **kwargs):
    """
        url    : /system/IPoperate/
        method : POST

    :param request:
            token:data.token,//用户密钥
            userId:data.userId,//id
            userIP:data.userIP,//操作的IP地址
            operating:data.operating

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType
    IP = datacheck.getIP(request)

    user1 = User.objects.get(pk=requestParam['userId'])
    userIP = IPSystem.objects.filter(userIP=requestParam['userIP'], user=user1)[0]
    if userType == '2':
        if requestParam['operating'] == '0' and userIP.isForbid == False:
            userIP.isForbid = True
            userIP.IPState = 1
            userIP.save()
            userLog = UserLog.objects.create(
                user=user,
                userIP=IP,
                operate='禁用IP'
            )
        elif requestParam['operating'] == '1' and userIP.isForbid == True:
            userIP.isForbid = False
            userIP.IPState = 0
            userIP.save()
            userLog = UserLog.objects.create(
                user=user,
                userIP=IP,
                operate='启用IP'
            )
        else:
            data = {
                'code': 1,
                'msg': 'operating error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def cpuInfo(request, *args, **kwargs):
    """
        url    : /system/status/
        method : POST

    :param request:
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            group:data.group,//0:本仓库，1：其他总，2：其他

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    if requestParam['token'] != '':
        user = datacheck.getUser(requestParam['token'])
        storehouse = Storehouse.objects.filter(user=user).first()
        # pdb.set_trace()
        cpuTimes = psutil.cpu_percent(percpu=False)
        cpu = int(round(cpuTimes))
        mem = psutil.virtual_memory()  ##内存
        totalMem = int(round(mem.total / 1024 / 1024 / 1024))
        usedMem = int(round(mem.used / 1024 / 1024 / 1024))
        use_perMem = int(round(mem.percent))

        caliche = psutil.disk_usage('/')  ##硬盘
        totalCaliche = int(round(caliche.total / 1024 / 1024 / 1024))
        usedCaliche = int(round(caliche.used / 1024 / 1024 / 1024))
        use_per = round((caliche.percent), 1)
        if storehouse.isMasterStore == True:
            system1 = System.objects.filter(storehouse=storehouse)

            if system1.exists():
                system = system1[0]
                system.cpu = cpu
                system.ram = use_perMem
                system.ramUsed = usedMem
                system.ramTotal = totalMem
                system.caliche = use_per
                system.calicheTotal = totalCaliche
                system.calicheUsed = usedCaliche
                system.save()
            else:
                system = System.objects.create(
                    storehouse=storehouse,
                    ram=use_perMem,
                    cpu=cpu,
                    ramTotal=totalMem,
                    caliche=use_per,
                    calicheTotal=totalCaliche,
                    ramUsed=usedMem,
                    calicheUsed=usedCaliche,
                )
        elif storehouse.isMasterStore == False:
            if storehouse.connectState == '2':
                filterDict = {}
                filterDict['storeIP'] = storehouse.storeIP
                filterDict['storePort'] = storehouse.storePort
                filterDict['storehouseName'] = storehouse.storehouseName
                filterDict['cpu'] = cpu
                filterDict['ram'] = use_perMem
                filterDict['ramTotal'] = totalMem
                filterDict['ramUsed'] = usedMem
                filterDict['caliche'] = use_per
                filterDict['calicheTotal'] = totalCaliche
                filterDict['calicheUsed'] = usedCaliche
                data1 = requests.post(
                    "http://" + storehouse.connectIP + ":" + storehouse.connectPort + "/api/system/" + 'status/',
                    data=filterDict)
                # data = json.loads(data1.text)
            system1 = System.objects.filter(storehouse=storehouse)

            if system1.exists():
                system = system1[0]
                system.cpu = cpu
                system.ram = use_perMem
                system.ramUsed = usedMem
                system.ramTotal = totalMem
                system.caliche = use_per
                system.calicheTotal = totalCaliche
                system.calicheUsed = usedCaliche
                system.save()
            else:
                system = System.objects.create(
                    storehouse=storehouse,
                    ram=use_perMem,
                    cpu=cpu,
                    ramTotal=totalMem,
                    caliche=use_per,
                    calicheTotal=totalCaliche,
                    ramUsed=usedMem,
                    calicheUsed=usedCaliche,
                )
                # pdb.set_trace()
        if requestParam['group'] == '0':
            system1 = System.objects.filter(storehouse=storehouse)
            system = system1[0]
            systemlists = []
            systemlist = {
                "storehouseName": system.storehouse.storehouseName,
                "ram": int(system.ram),
                "cpu": int(system.cpu),
                "ramTotal": int(system.ramTotal),
                "caliche": system.caliche,
                "calicheTotal": int(system.calicheTotal),
            }
            systemlists.append(systemlist)
            data = {
                "code": 0,
                "msg": "success",
                "totalNum": 1,
                "systemlist": systemlists,
            }
            logger_request.info(data)
            return JsonResponse(data)
        elif requestParam['group'] == '1':
            if storehouse.isMasterStore == False:
                data = {
                    "code": 0,
                    "msg": "storehouse not masterstore",
                    "totalNum": 0,
                    "systemlist": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
            elif storehouse.isMasterStore == True:
                # pdb.set_trace()
                storeConnectList = StorehouseConnect.objects.filter(masterStorehouseId=storehouse.id).filter(
                    ~Q(connectState='3'))
                if storeConnectList.exists():
                    storeConnectLists = []

                    storehouseLists = []

                    totalCpu = 0
                    totalRam = 0
                    usedRam = 0
                    totalCaliche = 0
                    usedCaliche = 0

                    for storeConnect in storeConnectList:
                        storehouse = Storehouse.objects.get(pk=storeConnect.subStorehouseId)

                        system1 = System.objects.filter(storehouse=storehouse)
                        if system1.exists():
                            system = system1[0]

                            totalRam = totalRam + int(system.ramTotal)
                            totalCaliche = totalCaliche + int(system.calicheTotal)
                            usedRam = usedRam + int(system.ramUsed)
                            usedCaliche = usedCaliche + int(system.calicheUsed)
                    if usedRam != 0 and usedCaliche != 0:
                        ramPer = round(usedRam / totalRam * 100)
                        calichePer = round(usedCaliche / totalCaliche * 100, 1)
                    else:
                        ramPer = 0
                        calichePer = 0

                    systemlists = []
                    storehouseList = {
                        "storehouseName": '',
                        "ram": ramPer,
                        "cpu": '',
                        "ramTotal": totalRam,
                        "caliche": calichePer,
                        "calicheTotal": totalCaliche,
                    }
                    systemlists.append(storehouseList)
                    data = {
                        "code": 0,
                        "msg": "success",
                        "totalNum": 0,
                        "systemlist": systemlists,
                    }
                    logger_request.info(data)
                    return JsonResponse(data)

                else:
                    data = {
                        "code": 0,
                        "msg": "no connect",
                        "totalNum": 0,
                        "systemlist": [],
                    }
                    logger_request.info(data)
                    return JsonResponse(data)
        elif requestParam['group'] == '2':
            if storehouse.isMasterStore == False:
                data = {
                    "code": 0,
                    "msg": "storehouse not masterstore",
                    "totalNum": 0,
                    "systemlist": [],
                }
                logger_request.info(data)
                return JsonResponse(data)
            elif storehouse.isMasterStore == True:
                # pdb.set_trace()
                storeConnectList = StorehouseConnect.objects.filter(masterStorehouseId=storehouse.id).filter(
                    ~Q(connectState='3'))
                if storeConnectList.exists():
                    storeConnectLists = []

                    storehouseLists = []

                    for storeConnect in storeConnectList:
                        storehouseList = Storehouse.objects.filter(pk=storeConnect.subStorehouseId)

                        for storehouse in storehouseList:
                            system1 = System.objects.filter(storehouse=storehouse)
                            if system1.exists():
                                system = system1[0]
                                storehouseList = {
                                    "storehouseName": system.storehouse.storehouseName,
                                    "ram": system.ram,
                                    "cpu": system.cpu,
                                    "ramTotal": system.ramTotal,
                                    "caliche": system.caliche,
                                    "calicheTotal": system.calicheTotal,
                                }
                                storehouseLists.append(storehouseList)

                        totalNum = len(storehouseLists)
                        result = storehouseLists[
                                 min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                          requestParam[
                                                                                                              'page'] *
                                                                                                          requestParam[
                                                                                                              'maxItem'])]
                    data = {
                        "code": 0,
                        "msg": "success",
                        "totalNum": totalNum,
                        "systemlist": result,
                    }
                    logger_request.info(data)
                    return JsonResponse(data)

                else:
                    data = {
                        "code": 0,
                        "msg": "no connect",
                        "totalNum": 0,
                        "systemlist": [],
                    }
                    logger_request.info(data)
                    return JsonResponse(data)
    if requestParam['token'] == '':
        storehouse = Storehouse.objects.get(storehouseName=requestParam['storehouseName'],
                                            storeIP=requestParam['storeIP'], storePort=requestParam['storePort'])
        system1 = System.objects.filter(storehouse=storehouse)
        if system1.exists():
            system = system1[0]
            system.cpu = requestParam['cpu']
            system.ram = requestParam['ram']
            system.ramUsed = requestParam['ramUsed']
            system.ramTotal = requestParam['ramTotal']
            system.caliche = requestParam['caliche']
            system.calicheTotal = requestParam['calicheTotal']
            system.calicheUsed = requestParam['calicheUsed']
            system.save()
        else:
            system = System.objects.create(
                storehouse=storehouse,
                ram=requestParam['ram'],
                cpu=requestParam['cpu'],
                ramTotal=requestParam['ramTotal'],
                caliche=requestParam['caliche'],
                calicheTotal=requestParam['calicheTotal'],
                ramUsed=requestParam['ramUsed'],
                calicheUsed=requestParam['calicheUsed'],
            )
        data = {
            "code": 0,
            "msg": "success",
        }
        logger_request.info(data)
        return JsonResponse(data)


def systemScreen(request, *args, **kwargs):
    """
        url    : /system/find/
        method : POST

    :param request:
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            storehouseName:data.storehouseName,//仓库名字
    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
                'storelist':[{
                    // 'time':null,//时间
                    'storehouseName':null,//仓库名称
                    'cpu':null,//CPU占用率
                    'ram':null,//内存占用率
                    'caliche':null,//硬盘
                }]
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam['token'])
    storehouse = Storehouse.objects.filter(user=user).first()
    # pdb.set_trace()
    filterDict = {}

    if requestParam['storehouseName'] != '':
        filterDict['storehouse__storehouseName__icontains'] = requestParam['storehouseName']

    if storehouse.isMasterStore == False:
        # storehouseSystem = System.objects.filter(**filterDict,storehouse=storehouse).first()
        # systemlist = {
        #     "storehouseName": storehouseSystem.storehouse.storehouseName,
        #     "ram": storehouseSystem.ram,
        #     "ramTotal": storehouseSystem.ramTotal,
        #     "caliche": storehouseSystem.caliche,            
        #     "calicheTotal": storehouseSystem.calicheTotal,
        # }        
        # data = {
        #     "code": 0,
        #     "msg": "success",
        #     "totalNum": 1,
        #     "systemlist":systemlist,
        # }
        # logger_request.info(data)
        # return JsonResponse(data)
        data = {
            "code": 0,
            "msg": "not masterStore",
            "totalNum": 0,
            "systemlist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)
    elif storehouse.isMasterStore == True:
        storeConnectList = StorehouseConnect.objects.filter(masterStorehouseId=storehouse.id).filter(
            ~Q(connectState='3'))
        # pdb.set_trace()
        if storeConnectList.exists():
            storeConnectLists = []

            storehouseLists = []

            for storeConnect in storeConnectList:
                storehouseList = Storehouse.objects.filter(storehouseName__icontains=requestParam['storehouseName'])

                for storehouse in storehouseList:
                    system1 = System.objects.filter(storehouse=storehouse)
                    system = system1[0]
                    storehouseList = {
                        "storehouseName": system.storehouse.storehouseName,
                        "ram": system.ram,
                        "cpu": system.cpu,
                        "ramTotal": system.ramTotal,
                        "caliche": system.caliche,
                        "calicheTotal": system.calicheTotal,
                    }
                    storehouseLists.append(storehouseList)

                totalNum = len(storehouseLists)
                result = storehouseLists[
                         min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                  requestParam['page'] *
                                                                                                  requestParam[
                                                                                                      'maxItem'])]
                data = {
                    "code": 0,
                    "msg": "success",
                    "totalNum": totalNum,
                    "systemlist": result,
                }
                logger_request.info(data)
                return JsonResponse(data)

        else:
            # storehouseSystem = System.objects.filter(**filterDict,storehouse=storehouse)
            # if storehouseSystem.exists():
            #     storesystem = storehouseSystem[0]
            #     systemlist = {
            #         "storehouseName": storesystem.storehouse.storehouseName,
            #         "ram": storesystem.ram,
            #         "ramTotal": storesystem.ramTotal,
            #         "caliche": storesystem.caliche,            
            #         "calicheTotal": storesystem.calicheTotal,
            #     }      
            #     data = {
            #         "code": 0,
            #         "msg": "success",
            #         "totalNum": 1,
            #         "systemlist":systemlist,
            #     }
            #     logger_request.info(data)
            #     return JsonResponse(data)
            # else:
            #     data = {
            #         "code": 0,
            #         "msg": "not find",
            #         "totalNum": 0,
            #         "systemlist":[],
            #     }
            #     logger_request.info(data)
            #     return JsonResponse(data)

            data = {
                "code": 0,
                "msg": "not connect",
                "totalNum": 0,
                "systemlist": [],
            }
            logger_request.info(data)
            return JsonResponse(data)
